package com.apes.scm.masterdata.car.service;

import com.apes.framework.api.DomainService;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.scm.masterdata.car.model.EmissionStandard;
import com.apes.scm.masterdata.car.repository.EmissionStandardRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * 功能：
 *
 * @Auther: linwz
 * @Date: 2018/7/25 11:42
 */
@Service("emissionStandardService")
public class EmissionStandardService extends DomainService {

    @Autowired
    EmissionStandardRepository emissionStandardRepository;

    public EmissionStandard save(SimpleRequest request) {
        EmissionStandard emissionStandard = request.getO(EmissionStandard.class);
        return emissionStandardRepository.saveAndFlush(emissionStandard);
    }

    public String delete(SimpleRequest request) {
        String id = request.get("id");
        Integer versions = request.get("version");
        EmissionStandard emissionStandard = request.getO(EmissionStandard.class);
        if (emissionStandard == null) throw new RuntimeException("排放标准【"+ id +"】在系统中不存在。");
        if (emissionStandard.getVersion() != versions) throw new RuntimeException("记录已更新或已删除，请重新提交！");
        emissionStandardRepository.delete(emissionStandard);
        return "删除成功";
    }

    /**
     * 功能：查询
     *
     * @param request
     */
    public Page<EmissionStandard> findAll(SimpleRequest request) {
        List<Map> filters = request.get("condition");
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        return emissionStandardRepository.findAll(JpaDsl.toCriteria(filters), PageRequest.of(request.get("page"), request.get("size"), sort));
    }

    /**
     * 功能：查询
     *
     * @param request
     */
    public Page<EmissionStandard> find(SimpleRequest request) {
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        return emissionStandardRepository.findAll(PageRequest.of(request.get("page"), request.get("size"), sort));
    }
}
